package libs

import (
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"github.com/google/uuid"
	"math/rand"
	"regexp"
	"strings"
	"time"
)

const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"

var seededRand = rand.New(rand.NewSource(time.Now().UnixNano()))

func stringWithCharset(length int, charset string) string {
	b := make([]byte, length)
	for i := range b {
		b[i] = charset[seededRand.Intn(len(charset))]
	}
	return string(b)
}

func UniqueToken(length int) string {
	return stringWithCharset(length, charset)
}

func UniqueID() (string, error) {
	uid, err := uuid.NewUUID()
	if err != nil {
		return "", err
	}
	return uid.String(), nil
}

const orderIDLength = 12

func GenerateOrderID(prefix string) string {
	timestamp := fmt.Sprintf("%d", time.Now().UnixNano())
	re := regexp.MustCompile(`[^a-zA-Z0-9]`)
	timestamp = re.ReplaceAllString(timestamp, "")
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	idPrefix := fmt.Sprintf("%c%c", 'A'+r.Intn(26), '1'+r.Intn(10))
	a := r.Intn(10)
	b := r.Intn(10)
	c := r.Intn(10)
	placeHolder := r.Intn(10)
	tail := fmt.Sprintf("%d%d%d", a, b, c)
	orderID := idPrefix + timestamp[:orderIDLength-3] + tail
	o := fmt.Sprintf("%s%s", prefix, orderID)
	return strings.ReplaceAll(o, ":", fmt.Sprintf("%d", placeHolder))
}

func GenerateSessionID() string {
	id, err := UniqueID()
	if err != nil {
		return ""
	}
	return base64.StdEncoding.EncodeToString([]byte(id))
}

func GenerateRatmuPermanentKey(cpuSerial string) string {
	hasher := sha256.New()
	hasher.Write([]byte(cpuSerial))
	hash := hasher.Sum(nil)
	hashHex := hex.EncodeToString(hash)
	repeatedHash := hashHex + hashHex + hashHex + hashHex
	return repeatedHash[:256]
}
